from pathlib import Path
from rime_utils.utils.timer import timer
from rime_utils.utils.wubi86_8105_map import wubi86_8105_map


def get_wubi_code(word: str) -> str:
    """将汉字转换为五笔编码"""
    code_parts = []
    for char in word:
        wubi_code = wubi86_8105_map[char]
        if len(wubi_code) == 3:
            code_parts.append(f"{wubi_code[:2]};{wubi_code[2:]}z")
        else:
            code_parts.append(f"{wubi_code[:2]};{wubi_code[2:]}")
    return ' '.join(code_parts)


def is_valid_word(word: str) -> bool:
    """检查词是否全部由可转换的汉字组成"""
    return all(char in wubi86_8105_map for char in word)


@timer
def convert(src_dir: Path, out_dir: Path, file_endswith_filter: str) -> None:
    """将拼音词库转换为五笔词库"""
    # 确保输出目录存在
    out_dir.mkdir(parents=True, exist_ok=True)

    # 处理每个符合条件的文件
    for file_num, file_path in enumerate(src_dir.glob(f'*{file_endswith_filter}'), 1):
        print(f'☑️  已加载第 {file_num} 份码表 » {file_path.name}')

        valid_entries = set()
        invalid_line_count = 0

        with open(file_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line or line[0] not in wubi86_8105_map:
                    continue

                parts = line.split('\t')
                if len(parts) < 3:
                    print(f"格式错误的行: {line}")
                    continue

                word, code, weight = parts[0], parts[1], parts[2]

                if not is_valid_word(word):
                    invalid_line_count += 1
                    continue

                wubi_code = get_wubi_code(word)
                valid_entries.add(f"{word}\t{wubi_code}\t{weight}\n")

        # 写入输出文件
        if valid_entries:
            output_path = out_dir / f"{file_path.stem}.yaml"
            with open(output_path, 'w', encoding='utf-8') as o:
                o.writelines(sorted(valid_entries))

            print(f"  成功转换 {len(valid_entries)} 条记录，跳过 {invalid_line_count} 条无效记录")


def get_user_input(prompt: str, default: str) -> str:
    """获取用户输入，提供默认值"""
    return input(f"{prompt}（默认：{default}）：").strip() or default


if __name__ == '__main__':
    proj_dir = Path(__file__).resolve().parent.parent
    print(f"项目目录: {proj_dir}")

    # 默认配置
    defaults = {
        'src_dir': 'src/cn_dicts',
        'out_dir': 'out/cn_dicts',
        'file_endswith_filter': '.dict.yaml'
    }

    # 获取用户输入
    src_dir = proj_dir / get_user_input("输入文件目录", defaults['src_dir'])
    out_dir = proj_dir / get_user_input("输出文件目录", defaults['out_dir'])
    file_endswith_filter = get_user_input("过滤的文件末尾", defaults['file_endswith_filter'])

    # 执行转换
    convert(src_dir, out_dir, file_endswith_filter)